#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <strings.h>
#include <cstdlib>

using namespace std;
//const string ip="127.0.0.1";  //回环地址,用于内部的
class UdpServer
{
public:
    UdpServer(const string&ip,uint16_t port)
    :_port(port),
    _ip(ip),
    _running(false),
    _sockfd(-1)
    {}
    void Init()
    {
        _sockfd = socket(AF_INET,SOCK_DGRAM,0); //创建套接字---》打开网卡
        if(_sockfd<0)
        {
            perror("socket failed!");
            exit(1);
        }
        struct sockaddr_in IPv4; //设置网络描述表
        bzero(&IPv4,sizeof(IPv4));  //初始化miaoshu
        IPv4.sin_family=AF_INET;    //设置网络通信
        IPv4.sin_addr.s_addr=inet_addr(_ip.c_str()); //设置ip
        IPv4.sin_port=htons(_port); //设置duankouhao
        //绑定
        int n=bind(_sockfd,(struct sockaddr*)&IPv4,sizeof(IPv4));
        if(n<0)
        {
            perror("Server bind failed !");
            exit(1);
        }
        cout<<_ip<<":"<<_port<<endl;
    }
    void Start()
    {
        _running=true;
        while(_running)
        {
                //读取数据
               char inbuffer[1024]={0};
               struct sockaddr_in buffer;
               bzero(&buffer,sizeof(buffer));
               socklen_t len=sizeof(buffer);
               ssize_t number=recvfrom(_sockfd,inbuffer,sizeof(inbuffer),0,(struct sockaddr*)&buffer,&len);
               inbuffer[number]='\0';
               cout<<'['<<"message:"<<inbuffer<<']'<<endl;
               cout<<'['<<"IP:"<<(string*)ntohs(buffer.sin_addr.s_addr)<<"---"<<"Port:"<<(string*)ntohs(buffer.sin_port)<<']'<<endl;
        }
        _running=false;
        
    }
    void Stop()
    {
        _running=false;
    }
    ~UdpServer()
    {}
private:
    //套接字描述符
    int  _sockfd;
    //端口号
    uint16_t _port;
    //ip地址
    string _ip;
    //是否启动后端服务
    bool _running;

};